package com.ar.studyapp;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayout;
import android.support.v7.widget.GridLayout.LayoutParams;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.ar.adapter.ResultAdapter;
import com.ar.bean.Exam;
import com.ar.datahandler.Examinator;
import com.ar.datahandler.StringJSONHandler;
import com.ar.network.NetworkUtility;
import com.ar.network.ParametersBuilder;
import com.ar.network.RestConnector;
import com.loopj.android.http.JsonHttpResponseHandler;

public class ResultActivity extends BaseActivity {
	private TextView tvScore;
	private TextView tvRatio;
	private int[] userAnswers;
	private ArrayList<Integer> ansIDs;
	private GridView gridView;
	private ResultAdapter resultAdapter;
	private StringJSONHandler jsonHandler;
	private ProgressDialog progressDialogOnLoad;
	private JsonHttpResponseHandler retryExamHandler;
	private Exam data;
	private Examinator examinator;
	private GridLayout gridLayout;
	private static int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void displayActivity() {
		setContentView(R.layout.activity_result);
	}

	@Override
	protected void initViews() {
		tvRatio = (TextView) findViewById(R.id.tvRatio);
		tvScore = (TextView) findViewById(R.id.tvScore);
		gridLayout = (GridLayout) findViewById(R.id.gridLayout);
		// gridView = (GridView) findViewById(R.id.gridView1);

	}

	@Override
	protected void initVariables() {
		jsonHandler = new StringJSONHandler();
	}

	@Override
	protected void initActions() {
		tvScore.setTextSize(TypedValue.COMPLEX_UNIT_PT, 14);
		tvRatio.setTextSize(TypedValue.COMPLEX_UNIT_PT, 14);
		userAnswers = this.getIntent().getExtras().getIntArray("user answers");
		data = getExam();
		// ansIDs =
		// this.getIntent().getExtras().getIntegerArrayList("answer IDs");
		// String result = this.getIntent().getExtras().getString("result");
		// Log.i("on_check", result);
		// resultHolder = jsonHandler.doRrepareForUserResult(result, ansIDs,
		// userAnswers);
		examinator = new Examinator(userAnswers, data);
		examinator.checkPoint(10);
		tvScore.setText("" + examinator.getMark());
		tvRatio.setText(examinator.getNumberOfcorrectAnswer() + "/"
				+ examinator.getNumberOfquiz());
		// resultAdapter = new ResultAdapter(this, examinator.getListDetail());
		// gridView.setAdapter(resultAdapter);
		// gridView.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// Intent intent = new Intent(getApplicationContext(),
		// ExamActivity.class);
		// intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		// intent.putExtra("position", position + 1);
		// intent.putExtra("ansFlags", examinator.getAnsFlag());
		// intent.putExtra("correct answers", examinator.getCorrectAnswers());
		// startActivity(intent);
		// }
		// });
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		final int screenHeight = dm.heightPixels;
		int rows = (int) ((float) (screenHeight * 6 / 10) / (float) 70);
		int total = examinator.getNumberOfquiz();
		int row = rows;
		int column = row / total;
		gridLayout.setColumnCount(column);
		gridLayout.setRowCount(row + 1);
		for (int i = 0, c = 0, r = 0; i < total; i++, r++) {
			if (r == row) {
				r = 0;
				c++;
			}
			TextView tv = new TextView(this);
			tv.setId(i);
			tv.setText(Html.fromHtml(examinator.getListDetail().get(i)));
			GridLayout.LayoutParams param = new GridLayout.LayoutParams();
			param.height = LayoutParams.WRAP_CONTENT;
			param.width = LayoutParams.WRAP_CONTENT;
			param.rightMargin = 50;
			param.topMargin = 30;
			param.setGravity(Gravity.CENTER);
			param.columnSpec = GridLayout.spec(c);
			param.rowSpec = GridLayout.spec(r);
			tv.setLayoutParams(param);
			gridLayout.addView(tv);
		}

//		for (int i = 0; i < gridLayout.getChildCount(); i++) {
//			gridLayout.getChildAt(i).setOnClickListener(
//					new View.OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							Intent intent = new Intent(getApplicationContext(),
//									ExamActivity.class);
//							intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//							intent.putExtra("position", gridLayout.getChildAt(i).getId() + 1);
//							intent.putExtra("ansFlags", examinator.getAnsFlag());
//							intent.putExtra("correct answers",
//									examinator.getCorrectAnswers());
//							startActivity(intent);
//						}
//					});
//		}

		retryExamHandler = new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(JSONObject response) {
				String jsonResponse = response.toString();
				StringJSONHandler jsonWorker = new StringJSONHandler();
				progressDialogOnLoad.dismiss();
				if (jsonWorker.checkError(jsonResponse) == false) {
					String title = new String(getCurrentSubjectName() + "-"
							+ getCurrentDiffName());
					Intent intent = new Intent(getBaseContext(),
							ExamActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra("title", title);
					intent.putExtra("data", jsonResponse.toString());
					startActivity(intent);
				} else {
					Toast.makeText(getApplicationContext(),
							jsonWorker.getErrorMessage(jsonResponse),
							Toast.LENGTH_LONG).show();
				}
			};

			@Override
			public void onFailure(Throwable error, String content) {
				progressDialogOnLoad.dismiss();
				NetworkUtility.showTimeOutDialog(getActivityInstance());
			}
		};
	}

	@Override
	protected void setUpActionBar() {
		super.setUpActionBar();
		getSupportActionBar().setDisplayShowHomeEnabled(false);
	}

	@Override
	public void onBackPressed() {
		showConfirmDialog();
	}

	private void showConfirmDialog() {
		AlertDialog.Builder restartAlertBuilder = new AlertDialog.Builder(this);
		restartAlertBuilder.setTitle("Warning");
		restartAlertBuilder
				.setMessage("Bạn muốn quay trở về màn hình trang chủ?");
		restartAlertBuilder.setCancelable(false);
		restartAlertBuilder.setPositiveButton("Ok", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent i = new Intent(getBaseContext(),
						CategoriesActivity.class);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
			}
		});
		restartAlertBuilder.setNegativeButton("Nope", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		AlertDialog restartAlertDialog = restartAlertBuilder.create();
		restartAlertDialog.show();

	}

	public void onClickRetry(View view) {
		if (NetworkUtility.checkNetworkState(getBaseContext())) {
			progressDialogOnLoad = ProgressDialog.show(this, "Loading exam",
					"Please wait …");
			RestConnector.get(NetworkUtility.GET_QUIZS_URL, ParametersBuilder
					.BuildGetQuizsParams(getCurrentCategoryId(),
							getCurrentDifficultId()), retryExamHandler);
		} else
			NetworkUtility.showNoNetworkDialog(getActivityInstance());
	}

	public void onClickHome(View view) {
		Intent i = new Intent(getBaseContext(), CategoriesActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
	}

	/*
	 * @Override public void onResponse(String jsonResponse) {
	 * progressDialogOnLoad.dismiss();
	 * if(jsonHandler.checkError(jsonResponse)==false){ //Log.d("onLoad",
	 * jsonResponse.toString()); Intent intent = new Intent(this,
	 * ExamActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	 * intent.putExtra("title", getCurrentSubjectName() + "-" +
	 * getCurrentDiffName()); intent.putExtra("data", jsonResponse.toString());
	 * startActivity(intent); } else { Toast.makeText(getApplicationContext(),
	 * jsonHandler.getErrorMessage(jsonResponse), Toast.LENGTH_LONG).show(); } }
	 * 
	 * @Override public void onRequestTimeOut() {
	 * progressDialogOnLoad.dismiss(); NetworkUtility.showTimeOutDialog(this); }
	 */
}
